package cn.piggy.gateway.core.socket.handler;

import cn.piggy.gateway.core.limiter.RedisLimiter;
import cn.piggy.gateway.core.socket.common.AgreementConstant;
import cn.piggy.gateway.core.socket.common.GatewayResult;
import cn.piggy.gateway.core.socket.parser.ResponseParser;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RequestLimitHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    private final Logger logger = LoggerFactory.getLogger(RequestLimitHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest request) throws Exception {
        String num = RedisLimiter.runLua().toString();
        logger.info("请求数 --> {}",num);
        if("0".equals(num)){
            DefaultFullHttpResponse response = new ResponseParser().parse(GatewayResult.buildError(AgreementConstant.ResponseCode._403.getCode(), "目前请求过多，请稍后再试！"));
            channelHandlerContext.channel().writeAndFlush(response);
        }else{
            request.retain();
            channelHandlerContext.fireChannelRead(request);
        }
    }
}
